//
//  VideoTool.m
//  cascade-realm
//
//  Created by QSC on 2/6/24.
//

#import "VideoAlertView.h"
#import <AVFoundation/AVFoundation.h>
@interface VideoAlertView()
@property(nonatomic,strong)NSURL * url;
@property (nonatomic,strong)UIView * playView;
@property (nonatomic,strong)AVPlayer * player;
@property (nonatomic,strong)AVPlayerLayer * playlayer;
@property (nonatomic,assign)BOOL playDidEnd;
@end
@implementation VideoAlertView
+(void)getFristFramFormUrl:(NSURL *)url sucess:(void(^)(UIImage *))success{
    SDImageCache *cache = [SDImageCache sharedImageCache];
    
    UIImage * cacheImg = [cache imageFromCacheForKey:url.path];
    
    if(cacheImg != nil){
        success(cacheImg);
        return;
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        AVAsset * asset = [AVAsset assetWithURL:url];
        
        AVAssetImageGenerator * g = [[AVAssetImageGenerator alloc] initWithAsset:asset];
        
        g.appliesPreferredTrackTransform = true;
        
        CMTime time = CMTimeMakeWithSeconds(0.0, 600);
        
        NSError * err = nil;
        
        CMTime actualTime;
        
        CGImageRef image = [g copyCGImageAtTime:time actualTime:&actualTime error:&err];
        
        UIImage * videoImg = [[UIImage alloc] initWithCGImage:image];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [cache storeImage:videoImg forKey:url.path completion:^{
                
                success(videoImg);
            }];
        });
    });
  
}

+(void)ShowAndPlayUrl:(NSURL *)url{
    
    VideoAlertView * videoView = [[VideoAlertView alloc] init];
    videoView.frame = [UIScreen mainScreen].bounds;
    videoView.url = url;
    [[UIApplication sharedApplication].keyWindow addSubview:videoView];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.6];
        
        self.playView = [UIView new];
        
        [self addSubview:self.playView];
        
        self.playView.layer.cornerRadius = 8;
        self.playView.clipsToBounds = YES;
 
        [self.playView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.centerY.equalTo(self);
            make.left.equalTo(self).offset(24);
            make.height.mas_equalTo(ScreenH * 0.7);
        }];
        
      

        
    }
    return self;
}

- (void)setUrl:(NSURL *)url{
    
    _url = url;
    
    AVPlayerItem * item = [[AVPlayerItem alloc] initWithURL:url];
    
    AVPlayer * player = [[AVPlayer alloc] initWithPlayerItem:item];
    
    AVPlayerLayer * layer = [AVPlayerLayer playerLayerWithPlayer:player];
    self.playlayer = layer;
    
    [self.playView.layer insertSublayer:layer atIndex:0];
    
    
    self.player = player;
    

    
    [item addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew) context:nil];
   
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(PlayDidEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:item];
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.playlayer.frame = self.playView.bounds;
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    CGPoint point = [touches.allObjects.firstObject locationInView:self];

    if (CGRectContainsPoint(self.playView.frame, point)) {
        if (self.player.timeControlStatus == AVPlayerTimeControlStatusPaused) {
            
            if (self.playDidEnd) {
                [self.player seekToTime:CMTimeMakeWithSeconds(0.0, 600)];
            }
            [self.player play];
        
        }else if (self.player.timeControlStatus == AVPlayerTimeControlStatusPlaying){
            [self.player pause];
         
        }
        return;
    }
   
    
    [self removePlayer];
    [self removeFromSuperview];
}

- (void)removePlayer{
    [self.player pause];
    [self.player replaceCurrentItemWithPlayerItem:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.player = nil;
}




-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
     
    
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem * avplayeritem = (AVPlayerItem *)object;
        AVPlayerStatus status = [[change objectForKey:@"new"] intValue];
       
        if (status == AVPlayerStatusReadyToPlay) {
           
            // 播放
            [self.player play];
            
            
        }else if (status == AVPlayerStatusFailed){
           
        }else{
           
        }
    }
}

- (void)PlayDidEnd{
    
    self.playDidEnd = YES;
}
@end
